package net.wanho.shop.task;

import lombok.RequiredArgsConstructor;
import net.wanho.shop.common.OrderConstant;
import net.wanho.shop.mapper.OrderMapper;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 这个类是：
 *
 * @author: MENG HU WANG
 * @date: 2025/1/1 15:17
 * @version: 1.0
 */

@Component
@RequiredArgsConstructor
public class OrderTask implements ApplicationContextAware {

    private final OrderMapper orderMapper;
    private ApplicationContext context;

    //    下单后，超过15分钟仍未支付，则判定为支付超时订单
    @Scheduled(cron = "0 0 1 * * ?")
    private void processTimeoutOrder() {
        // 查询超时未支付订单
        List<Integer> orderIds = orderMapper.selectTimeoutPay(LocalDateTime.now().minusMinutes(15), OrderConstant.WAIT_PAY);
        // 修改订单状态为已关闭
        if (orderIds != null) {
            orderMapper.updateTimeoutPay(orderIds, OrderConstant.CLOSED);
        }
    }


    // 每天凌晨1点检查
    @Scheduled(cron = "0 0 1 * * ?")
    public void processReceiveOrder() {
        // 查询超过7天未收货的订单
        List<Integer> ids = orderMapper.selectReceivePay(LocalDateTime.now().minusDays(7), OrderConstant.WAIT_RECEIVE);
        // 修改订单状态为已收货
        if (ids != null) {
            orderMapper.updateReceivePay(ids, OrderConstant.COMPLETED);

        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public ApplicationContext getContext() {
        return context;
    }

    public void setContext(ApplicationContext context) {
        this.context = context;
    }
}
